/*
 * Copyright 2011 OpenWAF.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.openwaf.client.core;


public abstract class Timer {


    private int id;
    private boolean repeating;
    public Timer(){
        repeating=false;
        id=-1;
    }
    public int getId(){
        return id;
    }
    public boolean isRepeating(){
        return repeating;
    }
    public abstract void run();
    
    private static native void clearInterval(int id) /*-{
        window.clearInterval(id);
    }-*/;
    private static native void clearTimeout(int id) /*-{
        window.clearTimeout(id);
    }-*/;
    private static native int setTimout(Timer timer,int delay)/*-{
        return window.setTimeout(function(){ timer.@com.openwaf.client.core.Timer::fire()(); },delay);
    }-*/;
    private static native int setInterval(Timer timer,int delay)/*-{
        return window.setInterval(function(){ timer.@com.openwaf.client.core.Timer::fire()(); },delay);
    }-*/;
    public void schedule(int delay){
        if(id==-1){
            id=setTimout(this, delay);
            repeating=false;
        }
        
    }
    public void scheduleRepeating(int delay){
        if(id==-1){
            id=setInterval(this, delay);
            repeating=true;
        }
    }
    public void cancel(){
        if(id==-1){
            return;
        }
        if(repeating){
            clearInterval(id);
        }else{
            clearTimeout(id);
        }
        id=-1;
    }
    public void fire(){
        if(!repeating){
         id=-1;
        }
        run();
    }

    
}
